package utils;

import com.tandil.seo.MainActivity;
import com.tandil.seo.R;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Vibrator;

public class AlarmReceiver extends BroadcastReceiver {
    public void onReceive(Context context, Intent intent) {
        Vibrator vibrator = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE);
        
        NotificationManager manger = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);

        Notification notification = new Notification(R.drawable.ic_launcher,
                context.getString(R.string.se_ha_agotado_el_tiempo), System
                        .currentTimeMillis());

        // The PendingIntent will launch activity if the user selects this
        // notification
        PendingIntent contentIntent = PendingIntent.getActivity(context, 0, new Intent(context, MainActivity.class), 0);
        notification.setLatestEventInfo(context, context.getString(R.string.tandilseo), context.getString(R.string.se_ha_agotado_el_tiempo), contentIntent);
        notification.flags |= Notification.FLAG_AUTO_CANCEL;        
        manger.notify(0, notification);

        Uri alert = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM);
        if(alert == null){
            // alert is null, using backup
            alert = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
            if(alert == null){  // I can't see this ever being null (as always have a default notification) but just incase
                // alert backup is null, using 2nd backup
                alert = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE);
            }
        }
        
        long[] pattern = {0, 200, 500, 200, 500, 200, 500};
        Ringtone r = RingtoneManager.getRingtone(context, alert);
        int i = 0;
        while (i<5){
            if (!r.isPlaying()) {
                r.play();
                vibrator.vibrate(pattern, -1);
                i++;
            }
        }
    }
}
